import { useMemo, useState } from 'react';
import { useDispatch } from 'react-redux';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Button, Drawer, Form, Input, message, Select } from 'antd';
import { useModel } from 'umi';

import ProTable from '@/components/ProTable';
import request from '@/utils/request';

import { crowdOptions, getColumnsByType, getGroupTagInfo } from './constants';
import CrowdExpandAdjustModal from './CrowdExpandAdjustModal';

const DrawerTitle = ({ title }) => {
  return (
    <>
      <p style={{ whiteSpace: 'nowrap' }}>{title}</p>
    </>
  );
};

const TagCrowdGroupDrawer = (props) => {
  const { handleCloseDrawer, crowdKey, propsGroupTagInfo } = props;
  const dispatch = useDispatch();
  const selectGroupTag = (payload) => {
    dispatch({ type: 'label/selectGroupTag', payload });
  };
  const { initialState } = useModel('@@initialState');
  const { dimName } = crowdOptions.find((item) => item.id === crowdKey) ?? {};
  const isMine = crowdKey?.indexOf('?') !== -1;
  const isExtend = crowdKey?.indexOf('extend') !== -1;
  const type = crowdKey?.indexOf('extend') !== -1 ? 'extend_crowd' : 'crowd';
  const [query, SetQuery] = useState();
  const [selectedGroupTag, setSelectedGroupTag] = useState();
  const [field, setField] = useState('name');
  const [inputValue, setInputValue] = useState();

  const useGetColumnByType = (type, operationRender) => {
    return useMemo(
      () => getColumnsByType(type, operationRender, isMine),
      [type, operationRender],
    );
  };
  const columns = useGetColumnByType(type, (_, groupTagsInfo) => {
    const { id, extend_crowd_id } = groupTagsInfo;
    const groupTagInfo = getGroupTagInfo(groupTagsInfo, isExtend);
    return (
      <Button
        type="link"
        onClick={() => {
          setSelectedGroupTag(groupTagInfo);
          if (groupTagInfo.customType === 1 || groupTagInfo.customType === 3) {
            selectGroupTag({
              ...groupTagsInfo,
              groupTagInfo,
              groupId: id || extend_crowd_id,
            });
            message.success('添加标签成功');
            setTimeout(handleCloseDrawer, 100);
          }
        }}
      >
        添加
      </Button>
    );
  });
  const onSearch = () => {
    if (field === 'name')
      SetQuery({ ...query, [isExtend ? 'crowd_name' : 'name']: inputValue });
    else
      SetQuery({ ...query, [isExtend ? 'extend_crowd_id' : 'id']: inputValue });
  };

  return (
    <>
      <Drawer
        title={<DrawerTitle title={dimName} />}
        open={true}
        width={600}
        closable={false}
        bodyStyle={{ padding: '0' }}
        onClose={handleCloseDrawer}
        extra={
          <Button
            type="link"
            href="https://wiki.in.zhihu.com/pages/viewpage.action?pageId=231183049"
            target="_blank"
          >
            DMP 标签口径详情
            <QuestionCircleOutlined />
          </Button>
        }
      >
        <Form
          name="search"
          onFinish={onSearch}
          autoComplete="off"
          layout="inline"
          style={{ padding: '20px 5px' }}
        >
          <Input.Group compact>
            <Select
              onChange={setField}
              value={field}
              options={[
                {
                  label: '名称',
                  value: 'name',
                },
                {
                  label: 'ID',
                  value: 'id',
                },
              ]}
            />
            <Input
              placeholder="请输入搜索内容"
              value={inputValue}
              onChange={(e) => {
                setInputValue(e.target.value);
              }}
              style={{ width: 'calc(100% - 200px)', margin: '0' }}
            />
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
          </Input.Group>
        </Form>
        <ProTable
          sticky={false}
          cardProps={{
            bodyStyle: { padding: '0' },
          }}
          columns={columns}
          params={query}
          request={async (params) => {
            const { current, pageSize } = params;
            const url = isMine
              ? `/api/dmp/crowd/${crowdKey}created=${initialState.currentUser.name}`
              : `/api/dmp/crowd/${crowdKey}`;
            const resp = await request(url, {
              params: {
                page: current,
                page_size: pageSize,
                ...params,
              },
            });
            return {
              success: resp.status === 0 ? true : false,
              total: resp.total,
              data: resp.data,
            };
          }}
          search={false}
          options={false}
          revalidateOnFocus={false}
        />
      </Drawer>
      <CrowdExpandAdjustModal
        groupTagInfo={selectedGroupTag}
        clearGroupTagInfo={() => setSelectedGroupTag(null)}
        selectGroupTag={selectGroupTag}
        dimId={crowdKey}
        propsGroupTagInfo={propsGroupTagInfo}
      />
    </>
  );
};

export default TagCrowdGroupDrawer;
